package com.dss.auto_deploy.util;

import cn.hutool.core.util.StrUtil;
import com.dss.auto_deploy.constants.AutoConstants;
import com.dss.auto_deploy.domain.AdmDockerDeploy;
import com.dss.auto_deploy.domain.Deploy;
import com.dss.auto_deploy.dto.SysFileDto;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.Charsets;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description:
 * @author: dongshoushan
 * @date: 2022年01月14日 15:26
 */
@Slf4j
public class FileUtils {

    /**
     * 写入总日志
     *
     * @param s
     * @throws IOException
     */
    public static void writeFileInRealTime(String s) throws IOException {
        System.out.println(s);
        FileWriter out = new FileWriter(AutoConstants.DEPLOY_INFO_PATH, true);
        out.write(s);
        out.write("\r\n");
        out.flush();
        out.close();
    }

    public static void writeDockerFileInRealTime(String s) throws IOException {
        System.out.println(s);
        FileWriter out = new FileWriter(AutoConstants.DOCKER_DEPLOY_INFO_PATH, true);
        out.write(s);
        out.write("\r\n");
        out.flush();
        out.close();
    }

    /**
     * 多个部署写入
     *
     * @param list
     * @throws IOException
     */
    public static void writeAllLog(List<Deploy> list, String s) throws IOException {
        for (Deploy deploy : list) {
            FileWriter out = new FileWriter(AutoConstants.DEPLOY_INFO_PATH_PREFIX + deploy.getId() + "部署日志.log", true);
            out.write(s);
            out.write("\r\n");
            out.flush();
            out.close();
        }
    }

    /**
     * 多个部署写入
     *
     * @param list
     * @throws IOException
     */
    public static void writeDockerAllLog(List<AdmDockerDeploy> list, String s) throws IOException {
        for (AdmDockerDeploy deploy : list) {
            FileWriter out = new FileWriter(AutoConstants.DOCKER_DEPLOY_INFO_PATH_PREFIX + deploy.getId() + "部署日志.log", true);
            out.write(s);
            out.write("\r\n");
            out.flush();
            out.close();
        }
    }

    /**
     * 重新部署
     *
     * @param list
     * @throws IOException
     */
    public static void recreateFileByPath(List<Deploy> list) throws IOException {
        for (Deploy deploy : list) {
            File file = new File(AutoConstants.DEPLOY_INFO_PATH_PREFIX + deploy.getId() + "部署日志.log");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        }
    }

    /**
     * 重新部署
     *
     * @param list
     * @throws IOException
     */
    public static void recreateDockerFileByPath(List<AdmDockerDeploy> list) throws IOException {
        for (AdmDockerDeploy deploy : list) {
            File file = new File(AutoConstants.DOCKER_DEPLOY_INFO_PATH_PREFIX + deploy.getId() + "部署日志.log");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        }
    }

    /**
     * 单个部署写入
     *
     * @param deploy
     * @param s
     * @throws IOException
     */
    public static void writeFileByPath(Deploy deploy, String s) throws IOException {
        FileWriter out = new FileWriter(AutoConstants.DEPLOY_INFO_PATH_PREFIX + deploy.getId() + "部署日志.log", true);
        out.write(s);
        out.write("\r\n");
        out.flush();
        out.close();
    }

    public static void writeDockerFileByPath(AdmDockerDeploy deploy, String s) throws IOException {
        FileWriter out = new FileWriter(AutoConstants.DOCKER_DEPLOY_INFO_PATH_PREFIX + deploy.getId() + "部署日志.log", true);
        out.write(s);
        out.write("\r\n");
        out.flush();
        out.close();
    }

    /**
     * 读取文件内容
     *
     * @param filePath
     * @param encoding
     * @return
     * @throws IOException
     */
    public static String readFileToString(String filePath, String encoding) throws IOException {
        return org.apache.commons.io.FileUtils.readFileToString(new File(filePath), Charsets.toCharset(encoding));
    }

    public static String readFileToString(String filePath, Charset charset) throws IOException {
        return org.apache.commons.io.FileUtils.readFileToString(new File(filePath), charset);
    }

    public static void copyFile(String path, String copyPath, String copyName) throws IOException {
        String fileName = copyPath + "/" + copyName;
        String string = readFileToString(path, StandardCharsets.UTF_8);
        File file = new File(copyPath);
        if (!file.exists()) {
            file.mkdir();
        }
        writeStringFile(fileName, string);
    }

    /**
     * 写入字符串到文件
     *
     * @param path
     * @param s
     * @throws IOException
     */
    public static void writeStringFile(String path, String s) {
        File file = new File(path);
        FileWriter out;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new FileWriter(path, true);
            out.write(s);
            out.write("\r\n");
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("文件写入异常{}", e.getMessage());
        } finally {

        }

    }

    public static void deleteAllFile(String filePath) {
        File file = new File(filePath);
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()) {
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f : files) {
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()) {
                deleteAllFile(f.getPath());
            } else {
                f.delete();
            }
        }
        //删除空文件夹 for循环已经把上一层节点的目录清空。
        file.delete();
    }

    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
    /**
     * <b>判断目录是否存在</b>
     */
    public static boolean isDirExist(String directory, ChannelSftp channel) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = channel.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if ("no such file".equals(e.getMessage().toLowerCase())) {
                isDirExistFlag = false;
            }
        }
        return isDirExistFlag;
    }

    /**
     * @param templateName 模板名称
     * @param path         生成路径
     * @param dataMap      参数
     * @throws Exception
     */
    public static void generateFileByTemplate(final String templateName, String path, String baseLocalPath, Map<String, Object> dataMap) throws Exception {
        //创建文件夹
        File base = new File(baseLocalPath);
        createFilePath(base);
        File file = new File(path);
        Template template = FreeMarkerTemplateUtils.getTemplate(templateName);
        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
        template.process(dataMap, out);
        fos.close();
        out.close();
    }

    public static void createFilePath(File file) {
        if (!file.exists()) {
            log.info("创建[{}]情况：{}", file.getAbsolutePath(), file.mkdirs());
        }
    }

    public static void createFilePath(String path) {
        File file = new File(path);
        if (!file.exists()) {
            log.info("创建[{}]情况：{}", file.getAbsolutePath(), file.mkdirs());
        }
    }

    public static String getFileNameByPath(String path) {
        File file = new File(path);
        return file.getName();
    }

    private static MimetypesFileTypeMap mimetypesFileTypeMap;

    /**
     * 下载http文件流
     *
     * @param urlStr
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    public static void downloadHttpFile(String urlStr, HttpServletRequest request, HttpServletResponse response, String fileName) {
        ServletOutputStream out = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //得到输入流
            inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = inputStreamToByte(inputStream);
            // 下载
            out = response.getOutputStream();
            long contentLength = getData.length;
            setResponse(fileName, contentLength, request, response);
            out.write(getData);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException("下载失败!");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //File、FileInputStream 转换为byte数组
    public static byte[] inputStreamToByte(InputStream inputStream) {
        try {
            byte[] buffer = new byte[1024];
            int len = 0;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.close();
            return bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("文件转换失败!");
        }
    }

    /**
     * 下载文件流
     *
     * @param file
     * @param request
     * @param response
     * @param fileName
     * @return
     */
    public static void downloadFile(File file, HttpServletRequest request, HttpServletResponse response, String fileName) {
        if (file != null && file.exists() && file.length() > 0L) {
            try {
                RandomAccessFile randomFile = new RandomAccessFile(file, "r");
                Throwable var5 = null;

                Object var54;
                try {
                    ServletOutputStream out = response.getOutputStream();
                    Throwable var7 = null;

                    try {
                        long contentLength = randomFile.length();
                        String range = request.getHeader("Range");
                        long start = 0L;
                        long end = 0L;
                        if (range != null && range.startsWith("bytes=")) {
                            String[] values = range.split("=")[1].split("-");
                            start = Long.parseLong(values[0]);
                            if (values.length > 1) {
                                end = Long.parseLong(values[1]);
                            }
                        }

                        int requestSize;
                        if (end != 0L && end > start) {
                            requestSize = Long.valueOf(end - start + 1L).intValue();
                        } else {
                            requestSize = 2147483647;
                        }

                        setResponse(fileName, contentLength, request, response);

                        randomFile.seek(start);

                        byte[] buffer;
                        for (int needSize = requestSize; needSize > 0; needSize -= buffer.length) {
                            buffer = new byte[1024];
                            int len = randomFile.read(buffer);
                            if (needSize < buffer.length) {
                                out.write(buffer, 0, needSize);
                            } else {
                                out.write(buffer, 0, len);
                                if (len < buffer.length) {
                                    break;
                                }
                            }
                        }

                        out.flush();
                        var54 = null;
                    } catch (Throwable var47) {
                        var7 = var47;
                        throw var47;
                    } finally {
                        if (out != null) {
                            if (var7 != null) {
                                try {
                                    out.close();
                                } catch (Throwable var46) {
                                    var7.addSuppressed(var46);
                                }
                            } else {
                                out.close();
                            }
                        }

                    }
                } catch (Throwable var49) {
                    var5 = var49;
                    throw var49;
                } finally {
                    if (randomFile != null) {
                        if (var5 != null) {
                            try {
                                randomFile.close();
                            } catch (Throwable var45) {
                                var5.addSuppressed(var45);
                            }
                        } else {
                            randomFile.close();
                        }
                    }

                }
            } catch (IOException var51) {
                log.debug(var51.getMessage(), var51);
                throw new RuntimeException(var51.getMessage());
            }
        } else {
            throw new RuntimeException("文件为空或不存在！");
        }
    }

    /**
     * @param fileName
     * @param contentLength
     * @param request
     * @param response
     * @return
     */
    public static void setResponse(String fileName, long contentLength, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType(getContentType("0.jpg"));
            boolean isPreview = "preview".equalsIgnoreCase(request.getParameter("source"));
            response.addHeader("Content-Disposition", (!isPreview ? "attachment; " : "") + "filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Accept-Ranges", "bytes");

            String range = request.getHeader("Range");
            if (range == null) {
                response.setHeader("Content-Length", String.valueOf(contentLength));
            } else {
                response.setStatus(206);
                long requestStart = 0L;
                long requestEnd = 0L;
                String[] ranges = range.split("=");
                if (ranges.length > 1) {
                    String[] rangeDatas = ranges[1].split("-");
                    requestStart = Long.parseLong(rangeDatas[0]);
                    if (rangeDatas.length > 1) {
                        requestEnd = Long.parseLong(rangeDatas[1]);
                    }
                }

                long length = 0L;
                if (requestEnd > 0L) {
                    length = requestEnd - requestStart + 1L;
                    response.setHeader("Content-Length", String.valueOf(length));
                    response.setHeader("Content-Range", "bytes " + requestStart + "-" + requestEnd + "/" + contentLength);
                } else {
                    length = contentLength - requestStart;
                    response.setHeader("Content-Length", String.valueOf(length));
                    response.setHeader("Content-Range", "bytes " + requestStart + "-" + (contentLength - 1L) + "/" + contentLength);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("response响应失败!");
        }
    }

    public static String getContentType(String fileName) {
        if (mimetypesFileTypeMap == null) {
            mimetypesFileTypeMap = new MimetypesFileTypeMap();
        }

        return mimetypesFileTypeMap.getContentType(fileName);
    }


    public static void createFile(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            log.info("创建[{}]情况：{}", file.getAbsolutePath(), file.createNewFile());
        }
    }

    public static void createFile(File file) throws IOException {
        if (!file.exists()) {
            log.info("创建[{}]情况：{}", file.getAbsolutePath(), file.createNewFile());
        }
    }

    /**
     * 将磁盘的多个文件打包成压缩包并输出流下载
     *
     * @param pathList
     * @param response
     */
    public static void zipDirFileToFile(List<SysFileDto> pathList, HttpServletResponse response) {
        log.info("开始进行压缩下载。。。");
        try {
            // 设置response参数并且获取ServletOutputStream
            ZipArchiveOutputStream zous = getServletOutputStream(response);
            for (SysFileDto sysFile : pathList) {
                String fileName = sysFile.getName();
                File file = new File(sysFile.getPath());
                InputStream inputStream = new FileInputStream(file);
                setByteArrayOutputStream(fileName, inputStream, zous);
            }
            zous.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("压缩下载完成。。。");
    }

    /**
     * 将网络url资源文件的多个文件打包成压缩包并输出流下载
     *
     * @param pathList
     * @param response
     */
    public static void zipUrlToFile(List<SysFileDto> pathList, HttpServletResponse response) {
        try {
            // 设置response参数并且获取ServletOutputStream
            ZipArchiveOutputStream zous = getServletOutputStream(response);

            for (SysFileDto sysFile : pathList) {
                String fileName = sysFile.getName();
                InputStream inputStream = getInputStreamFromUrl(sysFile.getPath());
                setByteArrayOutputStream(fileName, inputStream, zous);
            }
            zous.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static ZipArchiveOutputStream getServletOutputStream(HttpServletResponse response) throws Exception {

        String outputFileName = "文件" + new SimpleDateFormat("yyyy-MM-dd-HHmmss").format(new Date()) + ".zip";
        response.reset();
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        ServletOutputStream out = response.getOutputStream();

        ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
        zous.setUseZip64(Zip64Mode.AsNeeded);
        return zous;
    }

    private static void setByteArrayOutputStream(String fileName, InputStream inputStream, ZipArchiveOutputStream zous) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        byte[] bytes = baos.toByteArray();

        //设置文件名
        ArchiveEntry entry = new ZipArchiveEntry(fileName);
        zous.putArchiveEntry(entry);
        zous.write(bytes);
        zous.closeArchiveEntry();
        baos.close();
    }

    /**
     * 通过网络地址获取文件InputStream
     *
     * @param path 地址
     * @return
     */
    private static InputStream getInputStreamFromUrl(String path) {
        URL url = null;
        InputStream is = null;
        try {
            url = new URL(path);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

    /**
     * 获取指定文件夹下所有文件，不含文件夹里的文件
     *
     * @param dirFilePath 文件夹路径
     * @return
     */
    public static List<File> getAllFile(String dirFilePath) {
        if (StrUtil.isBlank(dirFilePath)) {
            return null;
        }
        return getAllFile(new File(dirFilePath));
    }

    public static List<File> getAllFileAndFolder(String dirFilePath) {
        if (StrUtil.isBlank(dirFilePath)) {
            return null;
        }
        // 创建一个File对象
        File directory = new File(dirFilePath);
        // 获取该目录下的所有文件和文件夹
        File[] files = directory.listFiles();
        return Arrays.asList(files);
    }


    /**
     * 获取指定文件夹下所有文件，不含文件夹里的文件
     *
     * @param dirFile 文件夹
     * @return
     */
    public static List<File> getAllFile(File dirFile) {
        // 如果文件夹不存在或着不是文件夹，则返回 null
        if (Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile()) {
            return null;
        }

        File[] childrenFiles = dirFile.listFiles();
        if (Objects.isNull(childrenFiles) || childrenFiles.length == 0) {
            return null;
        }

        List<File> files = new ArrayList<>();
        for (File childFile : childrenFiles) {
            // 如果是文件，直接添加到结果集合
            if (childFile.isFile()) {
                files.add(childFile);
            }
            //以下几行代码取消注释后可以将所有子文件夹里的文件也获取到列表里
//            else {
//                // 如果是文件夹，则将其内部文件添加进结果集合
//                List<File> cFiles = getAllFile(childFile);
//                if (Objects.isNull(cFiles) || cFiles.isEmpty()) continue;
//                files.addAll(cFiles);
//            }
        }
        return files;
    }

    public static MultipartFile getMultipartFile(String filePath) {
        File file = new File(filePath);
        return getMultipartFile(file);
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(file.getName(), "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        MultipartFile multipartFile = new CommonsMultipartFile(item);
        return multipartFile;
    }

    /**
     * 压缩下载，不包含srcPath目录
     *
     * @param srcPath src路径
     * @param zipPath zip路径
     * @throws IOException IOException
     */
    public static void zip(String srcPath, String zipPath) throws IOException {
        // 创建ZipOutputStream对象
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath));
        byte[] buf = new byte[1024];
        int len;
        // 打开要压缩的文件夹或文件
        File srcFile = new File(srcPath);
        if (srcFile.isDirectory()) {
            // 如果是目录，则递归压缩
            zipDir(srcFile, zos, "");
        } else {
            // 如果是文件，则压缩
            FileInputStream fis = new FileInputStream(srcFile);
            // 创建ZipEntry对象
            ZipEntry entry = new ZipEntry(srcFile.getName());
            // 将ZipEntry对象添加到ZipOutputStream对象中
            zos.putNextEntry(entry);
            // 将文件内容写入ZipOutputStream对象中
            while ((len = fis.read(buf)) > 0) {
                zos.write(buf, 0, len);
            }
            // 关闭ZipEntry对象
            zos.closeEntry();
            // 关闭文件输入流
            fis.close();
        }
        // 关闭ZipOutputStream对象
        zos.close();
    }

    private static void zipDir(File dir, ZipOutputStream zos, String basePath) throws IOException {
        // 获取文件列表
        File[] files = dir.listFiles();
        byte[] buf = new byte[1024];
        int len;
        for (File file : files) {
            if (file.isDirectory()) {
                ZipEntry zipEntry = new ZipEntry(basePath + file.getName() + "/");
                zos.putNextEntry(zipEntry);
                // 如果是目录，则递归压缩
                zipDir(file, zos, basePath + file.getName() + "/");
                zos.closeEntry();
            } else {
                // 如果是文件，则压缩
                FileInputStream fis = new FileInputStream(file);
                // 创建ZipEntry对象
                ZipEntry entry = new ZipEntry(basePath + file.getName());
                // 将ZipEntry对象添加到ZipOutputStream对象中
                zos.putNextEntry(entry);
                // 将文件内容写入ZipOutputStream对象中
                while ((len = fis.read(buf)) > 0) {
                    zos.write(buf, 0, len);
                }
                // 关闭ZipEntry对象
                zos.closeEntry();
                // 关闭文件输入流
                fis.close();
            }
        }
    }


    /**
     * 压缩zip，包含sourceFolderPath目录
     *
     * @param sourceFolderPath 源文件夹路径
     * @param zipFilePath      zip文件路径
     * @throws IOException IOException
     */
    public static void zipDirectory(String sourceFolderPath, String zipFilePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zos = new ZipOutputStream(fos);

        File sourceFolder = new File(sourceFolderPath);
        String baseName = sourceFolder.getName();

        zipFolder(sourceFolder, baseName, zos);


        zos.close();
        fos.close();
    }

    private static void zipFolder(File folder, String baseName, ZipOutputStream zos) throws IOException {
        File[] files = folder.listFiles();
        byte[] buffer = new byte[1024];

        for (File file : files) {
            if (file.isDirectory()) {
                String folderName = file.getName();
                String newBaseName = baseName + "/" + folderName;
                ZipEntry zipEntry = new ZipEntry(newBaseName + "/");
                zos.putNextEntry(zipEntry);
                zipFolder(file, newBaseName, zos);
                zos.closeEntry();
            } else {
                FileInputStream fis = new FileInputStream(file);
                ZipEntry zipEntry = new ZipEntry(baseName + "/" + file.getName());
                zos.putNextEntry(zipEntry);

                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }

                fis.close();
                zos.closeEntry();
            }
        }
    }

    /**
     * 从输入流中读取所有内容并转换为字符串。
     *
     * @param inputStream 输入流
     * @return 读取到的字符串内容
     */
    public static String readFromInputStream(InputStream inputStream) {
        if (inputStream == null) {
            throw new IllegalArgumentException("输入流不能为null");
        }

        StringBuilder resultStringBuilder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = br.readLine()) != null) {
                resultStringBuilder.append(line).append("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException("读取输入流时发生错误：" + e.getMessage(), e);
        }

        return resultStringBuilder.toString();
    }
}
